package com.mti.monitor.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mti.monitor.rst.Result;
import com.mti.monitor.service.AuthMonitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class AuthFilter implements Filter {

    @Autowired
    private AuthMonitorService authMonitorService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext sc = filterConfig.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if (cxt != null) {
            if (authMonitorService == null) {
                authMonitorService = cxt.getBean(AuthMonitorService.class);
            }
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getSession().getAttribute("user") != null) {

            /*if(!authMonitorService.checkAuth()) {
                response.setContentType("application/json;charset=UTF-8");
                JSONObject json = (JSONObject) JSON.toJSON(ResponseResult.fail(403, Constants.NO_LICENSE,null));
                response.getWriter().println(json.toString());
                return ;
            }*/

            filterChain.doFilter(request, response);
        } else {
            response.setContentType("application/json;charset=UTF-8");
            JSONObject json = (JSONObject) JSON.toJSON(Result.fail(400, "用户未登录"));
            response.getWriter().println(json.toString());
        }

    }

    @Override
    public void destroy() {
    }


}
